let express = require('express');
let router = express.Router();
let db = require('../conf');
let Token = require('../util/token');
let Auth = require('../util/auth');
let tools = require('../util');

//发送邮件
let nodemailer  = require('nodemailer');
let mailTransport = nodemailer.createTransport({
    // host : 'https://mail.qq.com',
    service: 'qq',
    secureConnection: true, // 使用SSL方式（安全方式，防止被窃取信息）
    auth : {
        user : '1308369732@qq.com',
        pass : 'owwtmgaoshrrgbdj'
    },
});

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'by-Server' });
});

/* GET send QQ_Email. */
router.get('/send', function(req, res, next) {
    let options = {
        from        : '"byjs" <1308369732@qq.com>',
        to          : '<1229218235@qq.com>',
        // cc         : ''  //抄送
        // bcc      : ''    //密送
        subject        : '一封来自Node Mailer的邮件',
        text          : '一封来自Node Mailer的邮件',
        html           : '<h1>你好，这是一封来自NodeMailer的邮件！</h1><p><img src="cid:00000001"/></p>',
        attachments :
            [
                {
                    filename: 'img1.png',            // 改成你的附件名
                    path: 'public/images/img1.png',  // 改成你的附件路径
                    cid : '00000001'                 // cid可被邮件使用
                },
                {
                    filename: 'img2.jpg',            // 改成你的附件名
                    path: 'public/images/img2.jpg',  // 改成你的附件路径
                    cid : '00000002'                 // cid可被邮件使用
                },
            ]
    };
    mailTransport.sendMail(options, function(err, msg){
        if(err){
            console.log(err);
            res.render('send', { title: err });
        }
        else {
            console.log(msg);
            res.render('send', { title: "已接收："+msg.accepted});
        }
    });

});

router.get('/socket', function(req, res, next) {
    res.render('socket', { title: 'socket.io' });
});
router.get('/add', function(req, res) {
    res.send({ title: 'add' });
});
/***
 * 获取用户信息
 */
router.get('/user', function(req, res) {
    try{
        // 定义一个虚拟的用户
       let lh =  new Auth({
            name: 'admin',
            password:111111,
        });
        let f = lh.encryption();
        console.log('用户密码加密后(与数据库对比)',f);
        lh.check().then(res => {
            console.log('用户的合法性',res);
        })
    } catch (e){
        console.log(e)
    }

    let temp = {
        name: 'lihao',
        admin: true
    };

    // 测试token
    const a = Token.createToken(temp);
    console.log('Token',a);
    try {
        console.log('获取对称加密的Header和Payload:',Token.decodeToken(a));
        console.log('验证token是否合法:',Token.checkToken(a));
    } catch (e){
        console.log(e)
    }

    const sql = 'SELECT * FROM by_user';
    db(sql,[],res,tools.data({
        message: 'dsss',
        data: [1,2,3]
    }))
});

// login 相关业务
router.post('/login',function(req,res){
    console.log(req.body);
    new Auth(req.body).check().then(function(result){
        if(result){
            let sql = "SELECT sysId,roles FROM by_user WHERE name=?;UPDATE by_user SET status='1' WHERE name=?;";
            console.log('用户名',req.body.username);
            db(sql,[req.body.username,req.body.username]).then(data=>{
                let temp = {
                    code: 0,
                    message: '登录成功',
                    success: true,
                    data: {
                        token:Token.createToken(data[0][0])
                    }
                };
                res.setHeader('Content-Type',"application/json");
                res.send(temp)
            }).catch(err=>{
                res.send({
                    code:10003,
                    success: false,
                    message: '系统错误,请联系管理员！'
                })
            })
        } else {
            let temp = {
                code: 3003,
                message: '用户名或密码不对',
                success: false,
                data: {
                    token: ''
                }
            };
            res.setHeader('Content-Type',"application/json");
            res.send(temp)
        }
     });
});

// 拉取用户信息
router.get('/user/info',function(req,res){
    let tempToken = req.query.token;
    let sysId = Token.decodeToken(tempToken).payload.data.sysId;
    let sql = 'SELECT sysId,roles,introduction,avatar FROM by_user WHERE sysId=?';
    db(sql,[sysId]).then(data=>{
        // 将用户的roles转化成数组返回
        let role_arr = data[0].roles.split('_');
        data[0].roles = role_arr;
        let temp = {
            code: 0,
            message: '获取用户信息成功',
            success: true,
            data: data[0]
        };
        res.setHeader('Content-Type',"application/json");
        res.send(temp)
    })
});

// 退出登录   /login/logout
router.post('/login/logout',function(req,res){
    let Authorization = req.headers['authorization'];
    let userId = Token.decodeToken(Authorization).payload.data.sysId;
    let sql = 'UPDATE by_user SET status="0" WHERE sysId=?';
    db(sql,[userId]).then(data=>{
        let temp = {
            code: 0,
            message: '用户成功登出',
            success: true,
            data: ''
        };
        res.setHeader('Content-Type',"application/json");
        res.send(temp)
    })
});


module.exports = router;
